package pl.wroc.pwr.docs.repos.webapp.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.h2.fulltext.FullText;
import org.h2.fulltext.FullTextLucene;

import pl.wroc.pwr.docs.repos.webapp.repo.Document;
import pl.wroc.pwr.docs.repos.webapp.repo.DocumentDao;
import pl.wroc.pwr.docs.repos.webapp.web.Message.STATUS;
import pl.wroc.pwr.docs.repos.webapp.web.Message.TYPE;


@WebServlet(urlPatterns="/documents")
public class DocumentsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Document> documents = null;
		ServletContext context = getServletContext();		
		DataSource ds = (DataSource) context.getAttribute("connectionPool");
		MessageQueue messages = ((MessageQueue) req.getSession().getAttribute("messages"));
		DocumentDao dao;
		Connection con = null;
		
		String searchQuery = req.getParameter("q");
	
		try {
			con = ds.getConnection();
			dao = new DocumentDao(con);
			
			if(searchQuery == null){
				documents = dao.getDocuments();

				if(documents.size() == 0){
					messages.push(new Message(STATUS.INFO, "Nie ma jeszcze żadnych dokumentów.", TYPE.PERSISTENT));
				}
				else {
					req.setAttribute("list", documents);
				}
				context.getRequestDispatcher("/documents.jsp").forward(req, resp);
			}
			else if(searchQuery.isEmpty()){
			    String referrer = req.getHeader("referer");
			    
			    if(referrer == null){
			    	referrer = "/documents";
			    }
			    messages.push(new Message(STATUS.ERROR, "Puste kryteria."));
			    resp.sendRedirect(referrer);
			    
			}
			else{
				ResultSet rs;
				 documents = new ArrayList<Document>();
				 
				if(req.getParameter("mode").equals("native"))
					rs = FullText.search(con, searchQuery, 0, 0);
				else
					rs = FullTextLucene.search(con, searchQuery, 0, 0);
				
				while(rs.next()){
					String query = rs.getString(1);
					System.out.println(query);
					documents.add(dao.getDocument(query));
				}
				
				if(documents.size() == 0){
					messages.push(new Message(STATUS.INFO, "Nie znaleziono dokumentów spełniających kryteria.", TYPE.PERSISTENT));
				}
				else {
					req.setAttribute("list", documents);
				}
				context.getRequestDispatcher("/documents.jsp").forward(req, resp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}